<?php


namespace app\common\service;

//use app\api\controller\Config;
use app\common\service\companyIndustry\realtime\RealtimeEmissionService;
use app\common\service\companyIndustry\simulation\SimulationEmissionService;
use think\facade\Config;
use think\Db;

/**
 * 烟气量
 * 具体包括：
 * 1、脱硝入口烟气量
 * 2、脱硫出口烟气量
 */
class FlugGasService extends BaseService
{
    /**
     * 实时企业脱硫、脱硝出口烟气量（单公司单排口分钟均值）
     * zhugeng 2019-07-11
     * @param $startTime
     * @param $endTime
     * @param $company_id
     * @param $drain_id
     * @param string $con_type
     * @return float|int
     * @throws \MongoDB\Driver\Exception\Exception
     */
    public function monitorSulfurExitSmoke($startTime, $endTime, $company_id, $drain_id, $con_type = 'SO2')
    {

//        $day_num = $this->diffBetweenTwoDays($startTime, $endTime) + 1;
        if (strlen($startTime) == 10 && strlen($endTime) == 10) {
            $startTime = $startTime . ' 00:00:00';
            $endTime = $endTime . ' 23:59:59';
        }
        $mongo = new \MongoDB\Driver\Manager(Config::get('mongodb_url'));
        if ($con_type == 'NO2') {
            $tab_name = 'company_industry_monitor_nitre_minute';
            $volume = '$aig_flue_flow';
            $volume_s = 'aig_flue_flow';
        } else {
            $tab_name = 'company_industry_monitor_sulfur_minute';
            $volume = '$export_flue_gas_volume';
            $volume_s = 'export_flue_gas_volume';
        }

        $document = [
            'aggregate' => $tab_name,
            'pipeline' => [
                [
                    '$project' => [
                        '_id' => 0,
                        'company_id' => 1,
                        'company_name' => 1,
                        'publish_time' => 1,
                        $volume_s => 1,
                        'drain_id' => 1,
                        'drain_name' => 1
                    ],
                ],
                [
                    '$match' => [
                        'publish_time' => [
                            '$gte' => $startTime,
                            '$lte' => $endTime,
                        ],
                        'company_id' => $company_id,
                        'drain_id' => $drain_id,
                    ]
                ],
                [
                    '$group' => [
                        '_id' => ['drain_id' => '$drain_id', 'drain_name' => '$drain_name', 'company_id' => '$company_id', 'company_name' => '$company_name'],
//                        '_id'        => ['company_id' => '$company_id','company_name' => '$company_name'],
                        's_emission' => ['$avg' => $volume],
                    ]
                ]
            ],
            'allowDiskUse' => true,
        ];
        $command = new \MongoDB\Driver\Command($document);
        $rows = $mongo->executeCommand('huanxin', $command)->toArray();
        $data = json_decode(json_encode($rows[0], 320), true)['result'];
        if (empty($data)) {
            return 0;
        } else {
            return $data[0]['s_emission'];//分钟均值
        }
    }

    /**
     * 实时企业脱硫、脱硝出口烟气量（设施天均值）
     * zhugeng  2019-07-13
     * @param $startTime
     * @param $endTime
     * @param $facility_id
     * @param $con_type
     */
    public function monitorSulfurExitSmokeDay($startTime, $endTime, $facility_id, $con_type = 'SO2')
    {
        $day_num = $this->diffBetweenTwoDays($startTime, $endTime) + 1;
        $startTime = $startTime . ' 00:00:00';
        $endTime = $endTime . ' 23:59:59';
        $mongo = new \MongoDB\Driver\Manager(Config::get('mongodb_url'));
        if ($con_type == 'NO2') {
            $tab_name = 'company_industry_monitor_nitre_minute';
            $volume = '$aig_flue_flow';
            $volume_s = 'aig_flue_flow';
        } else {
            $tab_name = 'company_industry_monitor_sulfur_minute';
            $volume = '$export_flue_gas_volume';
            $volume_s = 'export_flue_gas_volume';
        }
        $document = [
            'aggregate' => $tab_name,
            'pipeline' => [
                [
                    '$project' => [
                        '_id' => 0,
                        'facility_id' => 1,
                        'facility_name' => 1,
                        'company_name' => 1,
                        'publish_time' => 1,
                        $volume_s => 1,
                        'day' => ['$substr'=> ['$publish_time', 0, 10]]
                    ],
                ],
                [
                    '$match' => [
                        'publish_time' => [
                            '$gte' => $startTime,
                            '$lte' => $endTime,
                        ],
                        'facility_id' => (int)$facility_id,
//                        'drain_id'           => $drain_id,
                    ]
                ],
                [
                    '$group' => [
                        '_id' => ['day' => '$day','facility_id' => '$facility_id', 'facility_name' => '$facility_name'],
                        's_emission' => ['$avg' => $volume],
                    ]
                ]
            ],
            'allowDiskUse' => true,
        ];
        $command = new \MongoDB\Driver\Command($document);
        $rows = $mongo->executeCommand('huanxin', $command)->toArray();
        $data = json_decode(json_encode($rows[0], 320), true)['result'];
        if (empty($data)) {
            return 0;
        } else {
            return $data[0]['s_emission'] / $day_num;
        }
    }

    /**
     * 实时企业脱硫、脱硝出口烟气量（设施分钟均值）
     * zhugeng  2019-07-13
     * @param $startTime
     * @param $endTime
     * @param $facility_id
     * @param $con_type
     */
    public function monitorSulfurExitSmokeMinuteAvg($startTime, $endTime, $facility_id, $con_type = 'SO2')
    {
//        $day_num = $this->diffBetweenTwoDays($startTime, $endTime) + 1;
        $startTime = $startTime . ' 00:00:00';
        $endTime = $endTime . ' 23:59:59';
        $mongo = new \MongoDB\Driver\Manager(Config::get('mongodb_url'));
        if ($con_type == 'NO2') {
            $tab_name = 'company_industry_monitor_nitre_minute';
            $volume = '$aig_flue_flow';
            $volume_s = 'aig_flue_flow';
        } else {
            $tab_name = 'company_industry_monitor_sulfur_minute';
            $volume = '$export_flue_gas_volume';
            $volume_s = 'export_flue_gas_volume';
        }
        $document = [
            'aggregate' => $tab_name,
            'pipeline' => [
                [
                    '$project' => [
                        '_id' => 0,
                        'facility_id' => 1,
                        'facility_name' => 1,
                        'company_name' => 1,
                        'publish_time' => 1,
                        $volume_s => 1,
//                        'day' => ['$substr'=> ['$publish_time', 0, 10]]
                    ],
                ],
                [
                    '$match' => [
                        'publish_time' => [
                            '$gte' => $startTime,
                            '$lte' => $endTime,
                        ],
                        'facility_id' => $facility_id,
//                        'drain_id'           => $drain_id,
                    ]
                ],
                [
                    '$group' => [
                        '_id' => ['facility_id' => '$facility_id', 'facility_name' => '$facility_name'],
                        's_emission' => ['$avg' => $volume],
                    ]
                ]
            ],
            'allowDiskUse' => true,
        ];
        $command = new \MongoDB\Driver\Command($document);
        $rows = $mongo->executeCommand('huanxin', $command)->toArray();
        $data = json_decode(json_encode($rows[0], 320), true)['result'];
        if (!empty($data)) {
            return $data[0]['s_emission'];
        } else {
            return 0;
        }

    }

    /**
     * 实时企业脱硫脱硝单公司单排口N天每小时出口烟气量求和
     * zhugeng 2019-07-24
     * @param $startTime
     * @param $endTime
     * @param $company_id
     * @param $drain_id
     * @param string $con_type
     * @return mixed
     * @throws \MongoDB\Driver\Exception\Exception
     */
    public function monitorSulfurExitDrainSmokeHour($startTime, $endTime, $company_id, $drain_id, $con_type = 'SO2')
    {
        $startTime = $startTime . ' 00:00:00';
        $endTime = $endTime . ' 23:59:59';
        $mongo = new \MongoDB\Driver\Manager(Config::get('mongodb_url'));
        if ($con_type == 'NO2') {
            $tab_name = 'company_industry_monitor_nitre_minute';
            $volume = '$aig_flue_flow';
            $volume_s = 'aig_flue_flow';
        } else {
            $tab_name = 'company_industry_monitor_sulfur_minute';
            $volume = '$export_flue_gas_volume';
            $volume_s = 'export_flue_gas_volume';
        }
        $document = [
            'aggregate' => $tab_name,
            'pipeline' => [
                [
                    '$project' => [
                        '_id' => 0,
                        'drain_id' => 1,
                        'drain_name' => 1,
                        'company_id' => 1,
                        'company_name' => 1,
                        'publish_time' => 1,
                        $volume_s => 1,
                        'day' => ['$substr' => ['$publish_time', 0, 13]]
                    ],
                ],
                [
                    '$match' => [
                        'publish_time' => [
                            '$gte' => $startTime,
                            '$lte' => $endTime,
                        ],
                        'company_id' => (int)$company_id,
                        'drain_id' => (int )$drain_id,
                    ]
                ],
                [
                    '$group' => [
                        '_id' => ['day' => '$day', 'company_id' => '$company_id', 'company_name' => '$company_name', 'drain_id' => '$drain_id', 'drain_name' => '$drain_name'],
                        's_emission' => ['$sum' => $volume],
                    ]
                ],
                [
                    '$sort' => ['_id' => 1]
                ]
            ],
            'allowDiskUse' => true,
        ];
        $command = new \MongoDB\Driver\Command($document);
        $rows = $mongo->executeCommand('huanxin', $command)->toArray();
        $data = json_decode(json_encode($rows[0], 320), true)['result'];

        return $data;
    }

    /**
     * 实时企业脱硫脱硝单公司单设施N天每小时出口烟气量求和
     * zhugeng 2019-07-24
     * @param $startTime
     * @param $endTime
     * @param $facility_id 设施id
     * @param string $con_type 脱硫SO2脱硝NO2
     * @return float|int
     * @throws \MongoDB\Driver\Exception\Exception
     */
    public function monitorSulfurExitSmokeFacilityHour($startTime, $endTime, $facility_id, $con_type = 'SO2')
    {
        $startTime = $startTime . ' 00:00:00';
        $endTime = $endTime . ' 23:59:59';
        $mongo = new \MongoDB\Driver\Manager(Config::get('mongodb_url'));
        if ($con_type == 'NO2') {
            $tab_name = 'company_industry_monitor_nitre_minute';
            $volume = '$aig_flue_flow';
            $volume_s = 'aig_flue_flow';
        } else {
            $tab_name = 'company_industry_monitor_sulfur_minute';
            $volume = '$export_flue_gas_volume';
            $volume_s = 'export_flue_gas_volume';
        }
        $document = [
            'aggregate' => $tab_name,
            'pipeline' => [
                [
                    '$project' => [
                        '_id' => 0,
                        'facility_id' => 1,
                        'facility_name' => 1,
                        'company_name' => 1,
                        'publish_time' => 1,
                        $volume_s => 1,
                        'day' => ['$substr' => ['$publish_time', 0, 13]]
                    ],
                ],
                [
                    '$match' => [
                        'publish_time' => [
                            '$gte' => $startTime,
                            '$lte' => $endTime,
                        ],
                        'facility_id' => (int)$facility_id,
//                        'drain_id'           => $drain_id,
                    ]
                ],
                [
                    '$group' => [
                        '_id' => ['day' => '$day', 'facility_id' => '$facility_id', 'facility_name' => '$facility_name'],
                        's_emission' => ['$sum' => $volume],
                    ]
                ]
            ],
            'allowDiskUse' => true,
        ];
        $command = new \MongoDB\Driver\Command($document);
        $rows = $mongo->executeCommand('huanxin', $command)->toArray();
        $data = json_decode(json_encode($rows[0], 320), true)['result'];

        return $data;
    }


    /**
     * 清华方案排放量（单公司单排口排放量，表中存的是小时均值）
     * zhugeng 2019-07-24
     * @param $plan_number 预案编号
     * @param $control_mode_id 管控方式ID,1工业减排2车辆限行3施工管控4道路抑尘
     * @param tsinghua_plan_name 方案1
     * @param $company_id 公司id
     * @param $drain_id 排口id
     * @param string $con_type 脱硫SO2脱硝NO2
     */
    public function getQingHuaEmissionDrainDayAvg($plan_number, $control_mode_id, $tsinghua_plan_name, $company_id, $drain_id, $con_type = 'SO2')
    {
        if (strtoupper($con_type) == 'SO2') {
            $field = 'company_id,company_name,drain_id,drain_name,drain_so2_emission as tsinghua_emission';//实时企业
        }
        if (strtoupper($con_type) == 'NO2') {
            $field = 'id,company_id,company_name,drain_id,drain_name,drain_no2_emission as tsinghua_emission';//实时企业
        }
//        if (strtoupper($con_type) == 'TSP') {
//            $field = 'id,company_id,company_name,drain_id,drain_name,drain_tsp_emission as tsinghua_emission';
//        }
        $sql = 'select ' . $field . ' from control_plan_from_tsinghua_drain_details where control_mode_id = ' . $control_mode_id . ' and plan_number = "' . $plan_number . '" and tsinghua_plan_name = "' . $tsinghua_plan_name . ' "and company_id = "' . $company_id . ' "and drain_id = "' . $drain_id . '" group by drain_id order by drain_id asc';
        $list = Db::query($sql);
        if (!empty($list)) {
            $list[0]['tsinghua_emission'] = $list[0]['tsinghua_emission'] * pow(10, 6);//kg换算mg
        } else {
            $list[0]['tsinghua_emission'] = [];
        }
        return $list[0]['tsinghua_emission'];
    }

    /**
     * 运行浓度方案值（单公司单排口N天均值）
     * zhugeng 2019-07-25
     * @param $start_time 开始时间
     * @param $end_time 结束时间
     * @param $plan_number 预案编号
     * @param $control_mode_id 管控方式ID,1工业减排2车辆限行3施工管控4道路抑尘
     * @param $tsinghua_plan_name 预案名称应的名称
     * @param $company_id 公司id
     * @param $drain_id 排口id
     * @param string $con_type 脱硫SO2脱硝NO2
     * @param $is_realtime 是否是实时企业
     * @return float|int
     * @throws \MongoDB\Driver\Exception\Exception
     */
    public function beforeProjectValue($start_time, $end_time, $company_id, $drain_id, $con_type = 'SO2', $is_realtime, $qinghua_hour_avg)
    {
        //清华方案排放量
//        $emission               = new ControlEmissionService();
//        $qinghua_discharge = $emission->getReductionEmission($plan_number,$con_type,$object_name);//小时均值
//        foreach ($qinghua_discharge as $k => $v) {
//            if ($drain_id == $v['drain_id']) {
//                $qinghua_hour_avg = $v['plan_emissions'];
//            }
//        }
//        if (!isset($qinghua_hour_avg)) {
//            $qinghua_hour_avg = 1;
//        }
        if ($qinghua_hour_avg == 1) {
            $result = 1;
        } else {
//            $qinghua_day_avg = $qinghua_hour_avg * 24;
            //出口烟气量
            if ($is_realtime == 1) {
                //实时企业出口烟气量(分钟均值)
                $smoke = $this->monitorSulfurExitSmoke($start_time, $end_time, $company_id, $drain_id, $con_type);
                $result = $smoke != 0 ? $qinghua_hour_avg / $smoke / 60 : 1;
            } else {
                if ($con_type == 'SO2') {
                    $field = 'sum(emissions_so2)/24 as emissions,sum(operation_concentration_so2)/24 as operation';
                } else {
                    $field = 'sum(emissions_nox)/24 as emissions,sum(operation_concentration_nox)/24 as operation';
                }
                $sql = 'select '.$field.' from company_industry_monitor_simulation_hour_avg where company_id = ? and drain_id = ?';
                $info = Db::query($sql, array($company_id, $drain_id));
                if (!empty($info)) {
                    $smoke = $info[0]['emissions'] / $info[0]['operation'];//小时平均值
                    $result = $qinghua_hour_avg / $smoke;
                } else {
                    $result = 1;//上面返回0，0在下面作为分母不能计算（之前数据不对，先返回1，后面数据是对的）
                }
            }
        }
//        $result = $smoke != 0 ? $qinghua_day_avg/$smoke : 1;
        return $result;
    }

    /**
     * 运行效率方案值（单公司单排口N天均值）
     * zhugeng  2019-07-27
     * @param $startTime 开始时间
     * @param $endTime 结束时间
     * @param $plan_number 预案编号
     * @param $drain_id 排口id
     * @param string $type 脱硫SO2脱硝NO2
     * @param int $company_id 公司id
     * @return float|int
     * @throws \MongoDB\Driver\Exception\Exception
     */
    public function getCompanyFacilityOperatingiDscharge($startTime, $endTime, $drain_id, $type = 'SO2', $company_id, $is_realtime, $discharge_avg)
    {
        $day_num = $this->diffBetweenTwoDays(date('Y-m-d', strtotime($startTime)), date('Y-m-d', strtotime($endTime))) + 1;
        //清华排放量小时均值
//        $emission               = new ControlEmissionService();
//        $qinghua_discharge = $emission->getReductionEmission($plan_number,$type,$object_name);//小时均值
//        foreach ($qinghua_discharge as $k => $v) {
//            if ($drain_id == $v['drain_id']) {
//                $discharge_avg = $v['plan_emissions'];
//            }
//        }
//        if (!isset($discharge_avg)) {
//            $discharge_avg = 1;
//        }
//        $discharge_avg = $this->getQingHuaEmissionDrainDayAvg($plan_number,$control_mode_id,$tsinghua_plan_name,$company_id,$drain_id,$type);
        if ($discharge_avg != 0) {
            $discharge_all = $discharge_avg * 24 * $day_num;//N天总排放量
            $discharge_minute = $discharge_avg / 60;//分钟排放量

            if ($is_realtime == 1) {
                if ($type == 'SO2') {
                    $field = 'emissions';
                    $table = 'huanxin.company_industry_monitor_sulfur_minute';
                } else {
                    $field = 'emission';
                    $table = 'huanxin.company_industry_monitor_nitre_minute';
                }
                $opt = [
                    'projection' => [
                        '_id' => 0
                    ],
                ];
                $match = [
                    'publish_time' => ['$gte' => $startTime, '$lte' => $endTime],
                    'drain_id' => $drain_id,
                    'operating_efficiency' => ['$ne' => 1],
                ];
                $query = new \MongoDB\Driver\Query($match, $opt);//查询
                $cursor = $this->mongodb->executeQuery($table, $query)->toArray();
                $list = mongoObjToArray($cursor);
                $sum = '';
                if (!empty($list)) {
                    foreach ($list as $k => $v) {
                        $xialv = $v[$field] / (1 - $v['operating_efficiency']);
                        $sum += $xialv;
                    }
                    $result = 1 - ($discharge_all / $sum);
                } else {
                    $result = 1;
                }
            } else {
                if ($type == 'SO2') {
                    $colum = 'operating_efficiency_so2 as efficiency';
                } else {
                    $colum = 'operating_efficiency_nox as efficiency';
                }
                $sql = 'select ' . $colum . ' from company_industry_monitor_simulation_hour_avg where company_id = ? and drain_id = ?';
                $info = Db::query($sql, array($company_id, $drain_id));
                if (!empty($info)) {
                    $efficiency = $info[0]['efficiency'];//分钟效率
                } else {
                    $efficiency = 1;//上面返回0，0在下面作为分母不能计算（之前数据不对，先返回1，后面数据是对的）
                }
                $result = 1 - ($discharge_all / ($discharge_minute / (1 - $efficiency) * 60 * 24));
            }
        } else {
            $result = 1;
        }
        return $result;
    }

    /**
     * 脱硫脱硝运行浓度当前值平均值（管控开始，有几个小时算几个小时）
     * zhugeng 2017-07-15
     * @param $start_time  开始时间
     * @param $end_time   结束时间
     * @param $company_id 公司id
     * @param $drain_id 排口id
     * @param $con_type 脱硫SO2脱硝NO2
     * @param $is_realtime 是否是实时企业
     * @param $planNumber 预案编号
     */
    public function realtimeMonitorConcentrationNowHour($start_time, $end_time, $company_id, $drain_id, $con_type = 'SO2', $is_realtime, $planNumber)
    {
        $emssion = new ControlEmissionService();
        //排放量
        $emission = $emssion->getSingleDrainEmissionDetailsEveryHour($drain_id, $planNumber, 'control');
        $emission_all = '';
        if ($con_type == 'NO2') {
            if ($emission != false) {
                foreach ($emission as $k => $v) {
                    $emission_all += $v['nox_emissions'];
                }
                $emission_avg = $emission_all / count($emission);
            } else {
                $emission_avg = 1;
            }
        } else {
            if ($emission != false) {
                foreach ($emission as $k => $v) {
                    $emission_all += $v['so2_emissions'];
                }
                $emission_avg = $emission_all / count($emission);//小时均值排放量
            } else {
                $emission_avg = 1;
            }
        }
        if ($is_realtime == 1) {//实时企业
            //出口烟气量小时和
            $dischargeHour_all = $this->monitorSulfurExitDrainSmokeHour($start_time, $end_time, $company_id, $drain_id, $con_type);
            if (!empty($dischargeHour_all)) {
                $num = count($dischargeHour_all);
                $sum = '';
                foreach ($dischargeHour_all as $k => $v) {
                    $sum += $v['s_emission'];
                }
                //出口烟气量小时均值
                $dischargeHour_avg = $sum / $num;
                //当前值平均值
                $now_avg = $emission_avg / $dischargeHour_avg;
            } else {
                $now_avg = 1;
            }


        } else {//模拟企业
            //模拟企业烟气量
            if ($con_type == 'SO2') {
                $field = 'sum(emissions_so2)/24 as emissions,sum(operation_concentration_so2)/24 as operation';
            } else {
                $field = 'sum(emissions_nox)/24 as emissions,sum(operation_concentration_nox)/24 as operation';
            }
            $sql = 'select ' . $field . ' from company_industry_monitor_simulation_hour_avg where company_id = ? and drain_id = ?';
            $result = Db::query($sql, array($company_id, $drain_id));
            if (!empty($result) && $result[0]['emissions'] != 0 && $result[0]['operation'] != 0) {
                $smoke_avg = $result[0]['emissions'] / $result[0]['operation'];//烟气量小时均值
            } else {
                $smoke_avg = 1;//数据库没数据，烟气量返回1
            }
            //当前值平均值
            $now_avg = $emission_avg / $smoke_avg;
        }
        return $now_avg;
    }

    /**
     * 脱硫脱硝运行效率当前值平均值（管控开始，有几个小时算几个小时）
     * zhugeng 2017-07-27
     * @param $start_time
     * @param $end_time
     * @param $company_id
     * @param $drain_id
     * @param string $con_type
     * @param $is_realtime
     * @param $planNumber
     * @return float|int
     * @throws \MongoDB\Driver\Exception\Exception
     */
    public function realtimeMonitorEfficiencyNowHour($start_time, $end_time, $company_id, $drain_id, $con_type = 'SO2', $is_realtime, $planNumber)
    {
        $emssion = new ControlEmissionService();
        //排放量
        $emission = $emssion->getSingleDrainEmissionDetailsEveryHour($drain_id, $planNumber, 'control');
        $num = count($emission);
        $emission_all = '';
        if ($con_type == 'NO2') {
            if ($emission != false) {
                foreach ($emission as $k => $v) {
                    $emission_all += $v['nox_emissions'];
                }
            } else {
                $emission_all = 1;
            }

        } else {
            if ($emission != false) {
                foreach ($emission as $k => $v) {
                    $emission_all += $v['so2_emissions'];
                }
            } else {
                $emission_all = 1;
            }

        }
        if ($is_realtime == 1) {//实时企业
            //排放量/(1-效率)求和
            if ($con_type == 'SO2') {
                $table = 'company_industry_monitor_sulfur_minute';
            } else {
                $table = 'company_industry_monitor_nitre_minute';
            }

            $match = [
                'publish_time' => ['$gte' => $start_time, '$lte' => $end_time],
                'drain_id' => (int)$drain_id,
                'operating_efficiency' => ['$ne' => 1]
            ];
            $sqlEmission = [
                'aggregate' => $table,
                'pipeline' => [
                    [
                        '$match' => $match
                    ],
                    [
                        '$group' => [
                            '_id' => null,
                            'operating_efficiency' => [
                                '$sum' => [ //求和
                                    '$divide' => [ //相除
                                        '$emissions',
                                        [
                                            '$subtract' => [ //相减
                                                1, '$operating_efficiency'
                                            ]
                                        ]
                                    ]
                                ]
                            ],
                        ]
                    ],
                ],
                'cursor' => new \stdClass(),
            ];
            $commandEmission = new \MongoDB\Driver\Command($sqlEmission);
            $sulfurDataObj = $this->mongodb->executeCommand('huanxin', $commandEmission)->toArray();
            if (!empty($sulfurDataObj)) {
                $operatingEfficiency = mongoObjToArray($sulfurDataObj)[0]['operating_efficiency'];
                $efficiency_avg = $operatingEfficiency == 0 ? 1 : 1 - ($emission_all / $operatingEfficiency);
            } else {
                $efficiency_avg = 1;
            }


        } else {//模拟企业
            //模拟企业排放量
            if ($con_type == 'SO2') {
                $field = 'sum(emissions_so2)/24 as emissions,sum(operating_efficiency_so2)/24 as operation';
            } else {
                $field = 'sum(emissions_nox)/24 as emissions,sum(operating_efficiency_nox)/24 as operation';
            }
            $sql = 'select ' . $field . ' from company_industry_monitor_simulation_hour_avg where company_id = ? and drain_id = ?';
            $result = Db::query($sql, array($company_id, $drain_id));
            if (!empty($result)) {
                //排放量/(1-效率)求和
                $emissions_minute = $result[0]['emissions'] / 60 / (1 - $result[0]['operation']) * 60 * $num;
                if ($emissions_minute == 0) {
                    $efficiency_avg = 1;
                } else {
                    $efficiency_avg = 1 - ($emission_all / $emissions_minute);
                }
            } else {
                $efficiency_avg = 1;//数据库没数据，烟气量返回1
            }
        }
        return $efficiency_avg;
    }

    /**
     * 脱硫/脱硝单公司单排口运行浓度减排前值（管控前7天均值）
     * zhugeng 2019-07-19
     * @param $start_time 开始时间
     * @param $end_time 结束时间
     * @param $company_id 公司id
     * @param $drain_id 排口id
     * @param $con_type 脱硫SO2脱硝NO2
     * @param $plan_number 预案编号
     * @param $is_realtime  是否是实时企业
     */
    public function beforeConcentration($start_time, $end_time, $company_id, $drain_id, $con_type = 'NO2', $is_realtime, $emissions)
    {
        if ($is_realtime == 1) {
            //实时企业出口烟气量(有效分钟均值)
            $smoke = $this->monitorSulfurExitSmoke($start_time, $end_time, $company_id, $drain_id, $con_type);
            $smoke = $smoke * 60;//实时企业小时平均值
        } else {
            $sql = 'select gas_volume from company_industry_monitor_simulation_hour_avg where company_id = ? and drain_id = ?';
            $info = Db::query($sql, array($company_id, $drain_id));
            if (!empty($info)) {
                $smoke = $info[0]['gas_volume'];//模拟企业小时平均值
            }
        }
        //减排前排放量
//        $emssion_service = new ControlEmissionService();
//        $discharge = $emssion_service->getReductionEmission($plan_number,$con_type,$object_name);
//        $discharge = $emssion_service->getSingleDrainEmissionsDayAvg($drain_id,$plan_number);
        //运行浓度减排前值
//        foreach ($discharge as $k => $v) {
//            if ($drain_id == $v['drain_id']) {
//                $emissions = $v['before_emissions'];
//            }
//        }
//        if (!isset($emissions)) {
//            $emissions = 1;
//        }

        $before_value = $smoke != 0 ? $emissions / $smoke : 1;
        return $before_value;
    }

    /**
     * 减排前  脱硫脱硝 排口运行效率
     * @param string $plan_number 预案编号
     * @param int $drain_id 排口ID
     * @param string $type SO2 NO2
     * @param string $endDay 结束时间
     * @param int $daysNumber 天数
     * @return string
     * @throws \MongoDB\Driver\Exception\Exception
     * @author zhugeng 2019/07/25
     */
    public function getCompanyFacilityOperatingEfficiency($drain_id, $type = 'SO2', $endDay = 'yesterday', $daysNumber = 7, $is_realtime, $emissions)
    {
        if ($endDay == 'yesterday') {
            $startTime = date('Y-m-d', strtotime("-" . $daysNumber . " day")) . ' 00:00:00';
            $endTime = date('Y-m-d', strtotime("-1 day")) . ' 23:59:59';
        } else {
            $startTime = date('Y-m-d', strtotime($endDay) - ($daysNumber - 1) * 3600 * 24) . ' 00:00:00';
            $endTime = date('Y-m-d', strtotime($endDay)) . ' 23:59:59';
        }
        if ($type == 'SO2') {
            $table = 'company_industry_monitor_sulfur_minute';
            $colum = 'sum(operating_efficiency_so2)/24 as efficiency,sum(emissions_so2)/24 as emissions';
        } else {
            $table = 'company_industry_monitor_nitre_minute';
            $colum = 'sum(operating_efficiency_nox)/24 as efficiency,sum(emissions_nox)/24 as emissions';
        }
        if ($is_realtime == 1) {
            $match = [
                'publish_time' => ['$gte' => $startTime, '$lte' => $endTime],
                'drain_id' => (int)$drain_id,
                'operating_efficiency' => ['$nin' => [0, 1]],
            ];
            $sqlEmission = [
                'aggregate' => $table,
                'pipeline' => [
                    [
                        '$project' => [
                            '_id' => 1,
                            'drain_id' => 1,
                            'publish_time' => 1,
                            'operating_efficiency' => 1,
                            'emissions' => 1,
                        ],
                    ],
                    [
                        '$match' => $match
                    ],
                    [
                        '$group' => [
                            '_id' => null,
                            'operating_efficiency' => [
                                '$sum' => [ //求和
                                    '$divide' => [ //相除
                                        '$emissions',
                                        [
                                            '$subtract' => [ //相减
                                                1, '$operating_efficiency'
                                            ]
                                        ]
                                    ]
                                ],
                            ],
                            'emissions' => ['$sum' => '$emissions'],
//                            'count' => ['$sum' => 1]
                        ]
                    ],
                ],
                'cursor' => new \stdClass(),
            ];
            $commandEmission = new \MongoDB\Driver\Command($sqlEmission);
            $sulfurDataObj = $this->mongodb->executeCommand('huanxin', $commandEmission)->toArray();
            $operatingEfficiency = mongoObjToArray($sulfurDataObj);
//            $operatingEfficiency[0]['operating_efficiency'] = $operatingEfficiency[0]['operating_efficiency'] == 0 ? 1 : $operatingEfficiency[0]['operating_efficiency'];
            if (is_nan($operatingEfficiency[0]['operating_efficiency'])) {
                $result = 1;
            } else {
                if (!empty($operatingEfficiency)) {
                    $result = 1 - ($operatingEfficiency[0]['emissions'] / $operatingEfficiency[0]['operating_efficiency']);
                } else {
                    $result = 1;
                }
            }
        } else {
            $sql = 'select ' . $colum . ' from company_industry_monitor_simulation_hour_avg where drain_id = ?';
            $info = Db::query($sql, array($drain_id));
            if (!empty($info)) {
                $efficiency = $info[0]['efficiency'];//分钟效率平均值
                $emission = $info[0]['emissions'] / 60;//分钟排放量平均值
            } else {
                $efficiency = 1;//上面返回0，0在下面作为分母不能计算（之前数据不对，先返回1，后面数据是对的）
                $emission = 1;
            }
            if ($emissions != 0 && $emission != 0) {
                $result = 1 - $emissions / ($emission / (1 - $efficiency) * 60);
            } else {
                $result = 1;
            }
        }
        return $result;
    }

    /**
     * +----------------------------------------------------------
     * 10.4 获取单个公司包括排口的排放量
     * +----------------------------------------------------------
     * @param $companyId
     * @param string $endDay
     * @param int $daysNumber
     * @param string $emissionUnit
     * +----------------------------------------------------------
     * @return array|mixed
     * @throws \MongoDB\Driver\Exception\Exception
     * @author zhugeng 2019-08-08
     * +----------------------------------------------------------
     */
    public function getSingleCompanyDrainEmissionMinToHourAvg($companyId, $endDay = 'yesterday', $daysNumber = 7, $emissionUnit = 'kg')
    {
        try {
            $realtime = new RealtimeEmissionService();
            $simulation = new SimulationEmissionService();
            if ((int)$companyId == 1) {  //step1:实时企业
                //脱硫/TSP/脱硝
                $data = $realtime->getRealtimeSingleCompanyDrainEmissionMinToHourAvg((int)$companyId, $endDay, $daysNumber, $emissionUnit);
            } else {      //step2:模拟企业
                $data = $simulation->getSimulationSingleCompanyDrainEmissionHourAvg((int)$companyId, $emissionUnit);
            }
            return $data;
        } catch (\Exception $e) {
//            exception($e->getMessage() . '获取小时数据失败');
            return false;
        }
    }

    /**
     * 脱硫运行浓度
     * zhugeng 2019-07-11
     * @param $start_time
     * @param $end_time
     * @param $company_id
     * @param $type 天day   小时hour
     * @param $con_type 脱硫SO2脱硝NO2
     * @param $controlModeId 管控方式ID
     * @param $planNumber  预案编号
     * @param $tsinghuaPlanName 方案名称
     */
    public function monitorSulfurProjectValue($start_time, $end_time, $con_type, $controlModeId, $planNumber, $tsinghuaPlanName)
    {
        $data_emission = [];
        $Emission = new EmissionService();

//        $qinghua = $Emission->getSingleDrainEmissionDetailsEveryHour(1,$planNumber);
        //出口烟气量
        $data = $this->monitorSulfurExitSmokeMinuteAvg($start_time, $end_time, 3, $con_type);
//        $data = $this->beforeConcentration('2019-07-25','2019-07-31',7,15,'SO2','CZ2019-07-31 001号',0);
        if (!empty($data)) {
            foreach ($data as $k => $v) {
                $result = $Emission->getTsinghuaSingleCompanyDrainEmission($con_type, $controlModeId, $planNumber, $v['_id']['company_id'], $tsinghuaPlanName);
                if (!empty($result)) {
                    foreach ($result as $k1 => $v1) {
                        $data_emission[$k1] = ['company_name' => $v1['company_name'], 'drain_name' => $v1['drain_name'], 'tsinghua_emission' => $v1['tsinghua_emission'], 'inlet_gas_volume' => $v['s_emission'], 'project_value' => $value = $v1['tsinghua_emission'] / $v['s_emission']];
                    }
                }
            }
        }
        return $data_emission;
    }

    /**
     * 脱硫、脱硝出口烟气量分钟补填数(实时企业)
     * zhugeng  2019-07-16
     * @param $date_start 开始日期
     * @param $date_end 结束日期
     * @param $company_id 公司id
     * @param $drain_id 排口id
     */
    public function smokeComplement($date_start, $date_end, $company_id, $drain_id, $con_type = 'SO2')
    {
        $date_start = $date_start . '00:00:00';
        $date_end = $date_end . '23:59:59';
        if ($con_type == 'NO2') {
            $tab_name = 'huanxin.company_industry_monitor_nitre_minute';
            $colum = 'aig_flue_flow';
        } else {
            $tab_name = 'huanxin.company_industry_monitor_sulfur_minute';
            $colum = 'export_flue_gas_volume';
        }
        //链接MongoDB数据库（远程）
        $PDOManager = new \MongoDB\Driver\Manager(Config::get('mongodb_url'));
        $opt = [
            'projection' => [
                '_id' => 0
            ],
        ];
        $map = [
            "company_id" => (int)$company_id,//公司id
            "drain_id" => $drain_id,//排口id
            "publish_time" => ['$gte' => $date_start, '$lte' => $date_end]
        ];
        $query = new \MongoDB\Driver\Query($map, $opt);//查询
        $cursor = $PDOManager->executeQuery($tab_name, $query)->toArray();
        $list = json_decode(json_encode($cursor), true);
        $newList = [];
        for ($i = 0; $i < count($list); $i++) {
            $newList[date("Y-m-d H:i:00", strtotime($list[$i]['publish_time']))][] = $list[$i];
        }
        $minute = floor((strtotime($date_end) - strtotime($date_start)) % 86400 / 60);
        $k = $minute / count($newList);
        return $k;
    }

    /**
     * @author zhugeng 2019-05-07
     * @param $day1 开始日期
     * @param $day2 结束日期
     * @return float|int 相差天数
     */
    function diffBetweenTwoDays($day1, $day2)
    {
        $second1 = strtotime($day1);
        $second2 = strtotime($day2);

        if ($second1 < $second2) {
            $tmp = $second2;
            $second2 = $second1;
            $second1 = $tmp;
        }
        return ($second1 - $second2) / 86400;
    }

    //企业列表分页
    function page($page, $page_num)
    {
        if ($page > 0) {
            $limit = ($page - 1) * $page_num;
        } else {
            $limit = 0;
        }
        return $limit;
    }

}